//
// Created by 33145 on 2023/2/4.
//
#include "sylar/tcp_server.h"
#include "sylar/iomanager.h"
#include "sylar/log.h"

sylar::Logger::ptr g_logger = SYLAR_LOG_ROOT();

void run() {
  auto addr = sylar::Address::LookupAny("127.0.0.1:8088");
  // auto addr2 = sylar::UnixAddress::ptr(new sylar::UnixAddress("/tmp/unix_addr"));
  // auto add = sylar::IPAddress::Create("127.0.0.1", 8080);
  SYLAR_LOG_INFO(g_logger) << addr;
  // SYLAR_LOG_INFO(g_logger) << addr2;
  std::vector<sylar::Address::ptr> addrs;
  addrs.push_back(addr);
  // addrs.push_back(addr2);

  sylar::TcpServer::ptr tcp_server(new sylar::TcpServer);
  std::vector<sylar::Address::ptr> fails;
  while(!tcp_server->bind(addrs, fails)) {
    sleep(2);
  }
  tcp_server->start();
}

void test_server() {
  sockaddr_in addr;
  memset(&addr, 0, sizeof(addr));
  addr.sin_family = AF_INET;
  inet_pton(AF_INET, "0.0.0.0", &addr.sin_addr);
  addr.sin_port = htons(8080);

  int sock = socket(AF_INET, SOCK_STREAM, 0);
  bind(sock, (sockaddr*)&addr, sizeof(addr));
  listen(sock, 5);
  sockaddr_in clinet;
  socklen_t clinet_size = sizeof(clinet);
  int connfd = accept(sock, (sockaddr*)&clinet, &clinet_size);
  if (connfd > 0) {
    SYLAR_LOG_DEBUG(g_logger) << "connfd is : " << connfd;
    char buf[1024] = {};
    memset(buf, 0, sizeof buf);
    int ret = recv(connfd, buf, sizeof buf - 1, 0);
    SYLAR_LOG_DEBUG(g_logger) << ret << "  " << buf;
    SYLAR_LOG_DEBUG(g_logger) << errno;
    SYLAR_LOG_DEBUG(g_logger) << std::strerror(errno);
    int send_size = send(connfd, "hello world xxxxx", 17, 0);
    SYLAR_LOG_DEBUG(g_logger) << send_size;
  }
}

int main(int argc, char** argv) {
  sylar::IOManager iom(2);
  iom.schedule(run);
  // test_server();
  return 0;
}